<?php
namespace app\home\controller;

use think\Cache;
use think\Controller;
use think\Exception;
use think\Log;
use think\Session;

class Upload extends Base
{

   public function uploadImg(){
       try{
           $base_img=input("post.image");
           if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base_img, $result)){
               $type = $result[2];
               $new_file = "goods/upload/".date('Ymd',time())."/";
               if(!file_exists($new_file)){
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                   mkdir($new_file, 0777);
               }
               $new_file = $new_file.time().".{$type}";
               if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base_img)))){
                   $user_id=Session::get("bloguser")["user_id"];
                   #$data["user_img"]="http://www.it-yuan.com/".$new_file;
                   $data["user_img"]="http://localhost:8080/w_blog/public/".$new_file;
                   $res=model("BlogUser")->updateBlogUser($user_id,$data);
                   if($res!==false){
                       Session::set("bloguser",model("BlogUser")->getUserById($user_id));
                       return json(["code"=>1,"msg"=>"修改成功"]);
                   }
               }else{
                   return json(["code"=>-1,"msg"=>"修改失败"]);
               }
           }

       }catch (Exception $e){
            Log::record($e->getMessage());
            return json(["code"=>-1,"msg"=>"系统出错，请刷新页面"]);
       }
   }

}
